<template>
	<!-- 维保中年审梯保养合规情况 -->
	<view class="card" @click="cardClick">
		<view class="title">
			<view class="title_L">
				<text>维保中年审梯保养合规情况</text>
				<zb-tooltip arrowLeft="-180" placement="bottom-start" ref="tooltip">
					<image class="msg" src="@/static/images/index/q.png"></image>
					<view class="tipsContent" slot="content">
						<view class=""><text>正常：</text>年审梯近15天内有维保签字记录。</view>
						<view class=""><text>明天即将违规：</text>若今天结束前无新增维保签字记录，</view>
						<view class=""><text style="opacity: 0;">一二三四五：</text>年审梯明天将超出15天无保养。</view>
						<view class=""><text>已违规：</text>年审梯超15天无维保签字记录。</view>
					</view>
				</zb-tooltip>
			</view>
		</view>
		<view class="goBlack" v-if="d2.toopText2">
			<view class="left" @click.stop="goCircle(1)">
				<view> <text></text> 返回</view>
				<view><text>/</text>{{ d2.toolObj2.name || "" }}</view>
			</view>
			<view class="right" @click.stop="showUploadFile(2, d2.toolObj2.name)">
				<image src="@/static/images/download.png" mode="" />
				<view>下载数据</view>
			</view>
		</view>
		<view class="charts" @click="cardClose(1)">
			<l-echart class="ring rigBox" ref="d2" v-if="!d2.toopText2"></l-echart>
			<l-echart class="ring line-chart" ref="d2" v-else></l-echart>
			<!-- 数据列表 -->
			<view class="data-lable" v-if="d2.toopDesc">
				<view class="data-lable-item" v-for="(item, index) in d2.chartData.series" :key="index"
					@click="selectLegend(item, 'd2', index)">
					<view class="color" :style="{ background: item.show ? d2.colorsCopy[index] : '#ccc' }">
					</view>
					<view class="name">{{ item.name }}</view>
					<view class="num"
						:style="{ width: index == 1 ? '60rpx' : '', marginRight: index != 1 ? '20rpx' : '' }">
						{{ item.eleTotal }}台</view>
					<view class="eleTotal">{{ item.data }}%</view>
				</view>
			</view>
			<!-- 下钻 -->
			<view class="tooltips noRight" v-if="d2.tooplState2">
				<view class="tool_name">{{ d2.toolObj2.pName || "" }}</view>
				<view class="tool_data">
					<view :style="{ background: d2.toolObj2.color || '' }"></view>
					<view>{{ d2.toolObj2.name || "" }}：</view>
					<view>{{ d2.toolObj2.eleTotal || "0" }} ({{ d2.toolObj2.value || "0.0" }}%)</view>
				</view>
				<view class="tool_see" @click="seeClick(1, d2.toolObj2)" v-if="d2.toolObj2.eleTotal != 0">
					<image src="@/static/images/index/change.png"></image> 下钻
				</view>
			</view>

			<!-- 下钻查看电梯列表 -->
			<view class="tooltips noRight" :style="{ top: (d2.toElevatorListObj.offsetY - 30) + 'px' }"
				v-if="d2.toElevatorListToop">
				<view class="tool_name">{{ d2.toElevatorListObj.name || "" }}</view>
				<view class="tool_data">
					<view :style="{ background: d2.toElevatorListObj.color || '' }"></view>
					<view>{{ d2.toolObj2.name || "" }}：</view>
					<view>{{ d2.toElevatorListObj.data || "0" }}台</view>
				</view>
				<view class="tool_see" style="text-align: right;" @click.stop="toElevatorList"
					v-if="d2.toElevatorListObj.data != 0 && d2.toolObj2.name != '正常'">
					详情<uni-icons color="#0091FF" type="forward" size="14"></uni-icons>
				</view>
			</view>
		</view>
		<view class="loading-block" v-if="loading">
			<image class="img" src="@/static/images/loading.png" mode=""></image>
			<view class="text">加载中..</view>
		</view>
		<model :maskClick="false" width="508rpx" :visible="successVisible" title="下载成功" cancleTxt="复制链接"
			comfireTxt="直接打开" @cancle="modelRes(1)" @comfire="modelRes(2)" @close="successVisible = false">
			<view class="modelItem"> 你可以直接打开，或者复制链接至 </view>
			<view class="modelItem"> 电脑端浏览器下载。 </view>
		</model>
	</view>
</template>
<script>
import * as echarts from '@/subpages/components/lime-echart/static/echarts.min';
import { ringOpt, pieLine, setBarOpt2 } from '../utils/chart_opt.js';
import LEchart from '@/subpages/components/lime-echart/components/l-echart/l-echart.vue';
import { getStatus, getStatusExcel } from '@/apis/statistic.js';
import model from '@/components/model/index.vue';
export default {
	name: 'contractTotal',
	components: {
		LEchart,
		model
	},
	data() {
		return {
			// 维保中年审梯保养合规情况
			d2: {
				colors: ['#5FA9FF', '#FBCB92', '#FF89A8'],
				colorsCopy: ['#5FA9FF', '#FBCB92', '#FF89A8'],
				count: 0,
				toopDesc: true,
				linedata: {
					categories: [],
					series: [],
				},
				chartData: {
					series: [],
				},
				list: [],
				// tooltip状态
				tooplState2: false,
				// 返回按钮
				toopText2: false,
				toolObj2: {},
				toElevatorListToop: false,
				toElevatorListObj: {},
			},
			// 暂停维保电梯总览数据
			loseData: {},
			loading: false,
			downloadUrl: '',
			localPath: '',
			// 下载成功之后弹出框
			successVisible: false,
		};
	},
	props: {},
	created() {
		this.getStatus();
	},
	mounted() {

	},
	methods: {
		toElevatorList() {
			uni.navigateTo({
				url: '/subpages/statistics/elevatorList?type=5' + '&compliance=' + (this.d2.toolObj2.name == '明天即将违规' ? '2' : '3') + '&deptName=' + this.d2.toElevatorListObj.name,
			});
		},
		cardClick() {
			this.$refs.tooltip.close();
		},
		// 下载成功之后
		modelRes(type) {
			if (type == 1) {
				// 复制
				uni.setClipboardData({
					data: this.downloadUrl,
					success: () => {

					},
				});
				this.successVisible = false;
			} else {
				// #ifdef H5
				// eslint-disable-next-line no-undef
				sida.openUrl({ url: this.downloadUrl });

				//  #endif

				// 直接打开

				// #ifndef H5
				uni.openDocument({
					filePath: this.localPath,
					showMenu: true,
					fileType: 'xlsx',
					success: () => {
						console.log('打开文档成功');
					},
					fail: (err) => {
						console.log(err);
					},
				});
				// #endif

				this.successVisible = false;
			}
		},
		// 在保年审
		getStatus() {
			getStatus({}).then(res => {
				this.loading = false;
				this.d2.toopDesc = true;
				let arr = res.data || [];
				let list = [];
				for (const key in arr.maintainStatusData) {
					const item = arr.maintainStatusData[key];
					list.push(
						{
							name: '正常',
							eleTotal: item.value,
							data: item.pct,
							pName: '维保中年审梯保养合规情况',
							show: true
						});
				}
				list[1].name = '明天即将违规';
				list[2].name = '已违规';
				let colorsCopy = this.d2.colorsCopy;
				for (let i = 0; i < list.length; i++) {
					if (list[i].eleTotal == 0) {
						this['d2'].colors.splice(this['d2'].colors.indexOf(colorsCopy[i]), 1);
					}
				}
				this.d2.chartData.series = list;
				this.setRingChart('d2',);
			});
		},
		// 点击取消图例
		selectLegend(item, type, index) {
			let list = this[type].chartData.series;
			let colorsCopy = this[type].colorsCopy;
			item.show = !item.show;
			if (item.eleTotal == 0) return;
			if (!item.show) {
				this[type].colors.splice(this[type].colors.indexOf(colorsCopy[index]), 1);
			} else {
				let arr = [];
				list.forEach((it, idx) => {
					if (it.show && it.eleTotal != 0) {
						arr.push(colorsCopy[idx]);
					}
				});
				this[type].colors = arr;
			}
			if (this[type].colors.length == 0) return;
			this.setRingChart(type);
		},
		// 下载数据
		showUploadFile(status, name) {
			uni.showLoading({
				title: '下载中',
				icon: 'none',
			});
			let type = name == '正常' ? '1' : name == '明天即将违规' ? '2' : '3';
			getStatusExcel({ type }).then(res => {
				this.downloadUrl = res.data;
				this.submitPlan(res.data);
			});
		},
		// 下载文件
		submitPlan(url) {
			// #ifdef H5
			sida.openUrl({ url });
			uni.hideLoading();
			// #endif

			// #ifndef H5
			let str = url.split('/')[url.split('/').length - 1];
			uni.downloadFile({
				url,
				filePath: wx.env.USER_DATA_PATH + '/' + str,
				success: (res) => {
					console.log(res, '下载的文件');
					if (res.statusCode === 200) {
						uni.hideLoading();
						this.localPath = res.filePath;
						this.successVisible = true;
						uni.hideLoading();
					}
				},
				fail: () => {
					uni.hideLoading();
				},
			});
			// #endif
		},
		//  点击空白关闭下砖
		cardClose(val) {
			if (val === 1) {
				this.d2.tooplState2 = false;
				this.d2.toElevatorListToop = false;
			}
		},
		// 绘制环形图
		setRingChart(chart, data = {
			click: true
		}) {
			let list = this[chart].chartData.series;
			let chartData = [];
			for (let i = 0; i < list.length; i++) {
				if (list[i].show && list[i].eleTotal != 0) {
					chartData.push({
						value: list[i].data,
						eleTotal: list[i].eleTotal || '',
						name: list[i].name || '无',
						pName: list[i].pName
					});
				}
			}
			console.log('setRingChart', chart, chartData, this[chart].chartData);
			if (data.type == 'round') {
				this[chart].opts = pieLine({ color: this[chart].colors, data: chartData });
			} else {
				this[chart].opts = ringOpt({ color: this[chart].colors, data: chartData, type: 'ring' });
			}
			this.$nextTick(() => {
				if (!this.$refs[chart]) {
					return;
				}
				this.$refs[chart].init(echarts, chartF => {
					chartF.setOption(this[chart].opts, true);
					chartF.dispatchAction({
						type: 'highlight',
						seriesIndex: 0,
						dataIndex: 0
					});
					chartF.on('legendselectchanged', () => {
						// 处理图例点击导致选中与默认选中重叠问题
						chartF.dispatchAction({ type: 'downplay', seriesIndex: 0 });
					});
					chartF.on('mouseover', (e) => {
						// 当鼠标移除的时候 使默认的索引值去除默认选中
						if (e.dataIndex !== 0) {
							chartF.dispatchAction({ type: 'downplay', dataIndex: 0 });
						}
					});
					chartF.on('click', (e) => {
						setTimeout(() => {
							if (e.data.pName === '维保中年审梯保养合规情况') {
								this.d2.tooplState2 = true;
								this.d2.toolObj2 = { ...e.data, color: e.color };
							}
						}, 100);
					});
				});
			});
		},
		// 绘制条形图
		setLineChart(data) {
			this.$nextTick(() => {
				if (this.$refs['d2']) {
					this.$refs['d2'].init(echarts, (chartF) => {
						chartF.setOption(setBarOpt2(data), true);
						chartF.on('click', (e) => {
							setTimeout(() => {
								this.d2.toElevatorListToop = true;
								this.d2.toElevatorListObj = { name: e.name, color: e.color, data: e.data, offsetX: e.event.offsetX, offsetY: e.event.offsetY };
							}, 100);
						});
					});
				}
			});
		},
		//  下钻查看
		seeClick(type, objs = {}) {
			this.loading = true;
			this.d2.toopDesc = false;
			// 显示返回按钮
			this.d2.toopText2 = true;
			getStatus({}).then((res) => {
				this.loading = false;
				let obj = res.data || [];
				this.d2.colors = ['#5FA9FF', '#FBCB92', '#FF89A8',];
				// 关闭tooltips
				this.d2.tooplState2 = false;
				this.d2.list = obj;
				let categories = [];
				// x轴数据堆叠图
				let series = [
					{
						type: 'bar',
						data: [],
						itemStyle: {
							color: objs.color,
						},
					}
				];
				let data = {
					'正常': 1,
					'明天即将违规': 2,
					'已违规': 3,
				};
				for (const key in obj.maintainStatusBarChartData[data[objs.name]]) {
					const item = obj.maintainStatusBarChartData[data[objs.name]][key];
					categories.push(key);
					series[0].data.push(item);
				}
				this.setLineChart({ categories, series, name: objs.name });
			});
		},
		//  下钻返回
		goCircle() {
			this.loading = true;
			this.d2.toopText2 = false;
			this.d2.list = [];
			this.getStatus();
		},
	}
};
</script>

<style lang="scss" scoped>
@import './stat.scss';
.noRight {
	right: 0;
}

.rigBox {
	width: 320rpx;
}

.line-chart {
	width: 100%;
}

.data-lable {
	width: 100%;
	padding: 0 !important;
}
</style>